<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport"
          content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>商品信息</title>
    <script src="https://cdn.jsdelivr.net/npm/vue@2.7.16/dist/vue.js"></script>
    <link rel="stylesheet" href="./css/index.css">
    <style>

        a {
            text-decoration: none;
        }

        h4, p {
            font-size: 14px;
            color: #0b2e13;
        }

        p {
            color: #e11818;
        }

        button {
            border: none;
            padding: 10px 0;
            background: #d51b1b;
            color: white;
            box-shadow: 0 0 3px 1px #881d1d;
            cursor: pointer;
        }

        button:hover {
            box-shadow: none;
        }

        button:active {
            box-shadow: 0 0 5px 2px #881d1d inset;
        }

        .commodity {
            display: flex;
            flex-direction: column;

            gap: 10px;
            width: max-content;
            max-width: 80%;
            margin: 10px auto 0;
        }
    </style>
</head>
<body>
<div id="root">

    <div class="commodity">
        <img :src="cartData.src" alt="">
        <h4>{{ cartData.name }}</h4>
        <p>￥{{ cartData.price }}</p>
        <form action="">
            <span>-</span>
            <input class="pNum" type="text" value="1">
            <span>+</span>
        </form>
        <button @click="addCart(cartData.id)">点击添加购物车</button>
    </div>
</div>
<script>
    let vm = new Vue({
        el: "#root",
        data() {
            return {
                cartData: JSON.parse(sessionStorage.getItem('thisP'))
            }
        },
        methods: {
            addCart(id) {
                let p = []
                const num = document.querySelector('.pNum').value
                if (!localStorage.getItem('p')) {
                    p.push({pid: id, number: num})
                } else {
                    p = JSON.parse(localStorage.getItem('p'))
                    if (this.pFind(p, id) !== false) {
                        console.log(this.pFind(p, id))
                        p[this.pFind(p, id)].number = p[this.pFind(p, id)].number * 1 + num * 1
                    } else {
                        p.push({pid: id, number: num})
                    }
                }
                localStorage.setItem('p', JSON.stringify(p))
                location.href = 'cart.html'
            },
            pFind(pArr, id) {
                let bool = false
                pArr.forEach((e, index) => {
                    if (e.pid === id) bool = index;
                })
                return bool
            },

        },
        mounted() {

        }
    })
</script>

</body>
</html>